//
//  UIButton+ImageTitleSapce.m
//  LesDo
//
//  Created by 陈如意on 16/2/17.
//  Copyright © 2016年 xin wang. All rights reserved.
//

#import "UIButton+ImageTitleSapce.h"

@implementation UIButton (ImageTitleSapce)

- (void)layoutButtonWithEdgeInsetsStyle:(MKButtonEdgeInsetsStyle)style imageTitleSpace:(CGFloat)space {
    
    // 1. 得到imageView和titleLabel的宽高
    CGFloat imageWidth = self.imageView.frame.size.width;
    CGFloat imageHeight = self.imageView.frame.size.height;
    
    CGFloat labelWidth = 0.0;
    CGFloat labelHeight = 0.0;
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        // 由于ios8中titleLabel的size为0,用下面的这种设置
        labelWidth = self.titleLabel.intrinsicContentSize.width;
        labelHeight = self.titleLabel.intrinsicContentSize.height;
    } else {
        
        labelWidth = self.titleLabel.frame.size.width;
        labelHeight = self.titleLabel.frame.size.height;
        
    }
    
    // 2. 声明全局的imageEdgeInsets和labelEdgeInsets
    UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
    UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
    
    
    // 3. 根据style和space 得到imageEdgeInsets和labelEdgeInsets的值
    
    switch (style) {
        case MKButtonEdgeInsetsStyleTop:{
            imageEdgeInsets = UIEdgeInsetsMake(-labelHeight - space, 0, 0, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, -imageHeight - space, 0);
            
        }
            break;
            
        case MKButtonEdgeInsetsStyleLeft:{
            imageEdgeInsets = UIEdgeInsetsMake(0 ,0, 0, space / 2);
            labelEdgeInsets = UIEdgeInsetsMake(0, space / 2, 0, - space / 2 );
            
        }
            
            break;
        case MKButtonEdgeInsetsStyleBottom:{
            imageEdgeInsets = UIEdgeInsetsMake(0 , 0, - labelHeight - space, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(-imageHeight - space, -imageWidth, 0, 0);
            
        }
            
            break;
        case MKButtonEdgeInsetsStyleRight:{
            imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + space, 0, -labelWidth - space );
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWidth - space, 0, imageWidth + space);
            
        }
            break;
        default:
            break;
    }
    
    // 4.赋值
    self.titleEdgeInsets = labelEdgeInsets;
    self.imageEdgeInsets = imageEdgeInsets;
}


@end
